//
//  KVComposeViewController.swift
//  KVBestMicroblog
//
//  Created by 李康卫 on 16/7/28.
//  Copyright © 2016年 李康卫. All rights reserved.
//

import UIKit
import SVProgressHUD

class KVComposeViewController: UIViewController {
    ///保存toolBar的元素
    var toolBarBtns = [UIButton]()
    
    override func viewDidLoad() {
        self.view.backgroundColor = UIColor.blueColor()
        setupNagationItem()
        setupTextView()
        setupToolBar()
        setupRestLenghtLabel()
        //监听键盘的改变设置UItoolBar跟随键盘一起偏移
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChangeFrameNotification:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(true)
        //呼出键盘
        self.textView.becomeFirstResponder()
    }
    //注销通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    @objc private func keyBoardChangeFrameNotification(notification: NSNotification) {
        /*
        UIKeyboardAnimationDurationUserInfoKey = "0.4";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 1076}, {375, 258}}";
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
        userInfo
        UIKeyboardAnimationDurationUserInfoKey = "0.25";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
        */

        //动画时间
        let animationTime = notification.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]!.doubleValue
        let toolBarOffsetY = notification.userInfo!["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue.origin.y
        
        print(notification.userInfo!["UIKeyboardAnimationDurationUserInfoKey"])
        
        let offsetY = UIScreen.height() - toolBarOffsetY
        //键盘改变是使toolBar约束跟新
        self.toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view).offset(-offsetY)
        }
        UIView.animateWithDuration(animationTime) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
//        UIView.animateWithDuration(animationTime, delay: animationTime, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
//            self.toolBar.snp_updateConstraints { (make) -> Void in
//                make.bottom.equalTo(self.view).offset(-offsetY)
//            }
//            }, completion: nil)
    }
    //设置textView
    private func setupTextView() {
        self.view.addSubview(textView)
        self.textView.showsHorizontalScrollIndicator = true
        if textView.dragging {
            textView.resignFirstResponder()
        }
    }
    //设置导航栏
    private func setupNagationItem() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        //设置tiltleView
        self.navigationItem.rightBarButtonItem?.enabled = false
        self.navigationItem.titleView = titleView
    }
    //设置
    private func setupToolBar() {
//        添加toolbar
        self.view.addSubview(toolBar)
        //添加子控件
        addToolBarSubViews()
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.equalTo(self.view)
            make.height.equalTo(44)
            make.bottom.equalTo(self.view)
        }
    }
    private func addToolBarSubViews() {
        
        var items = [UIBarButtonItem]()
        let itemSettings = [
            ["imageName": "compose_toolbar_picture","click":"toolbar"],
            ["imageName": "compose_trendbutton_background","click":"trendbutton"],
            ["imageName": "compose_mentionbutton_background","click":"mentionbutton"],
            ["imageName": "compose_keyboardbutton_background","click":"emoticonbutton:"],
            ["imageName": "compose_add_background","click":"add"]
        ]
        for (_,imageDic) in itemSettings.enumerate() {
            let imgName = imageDic["imageName"]
//            let img =  UIImage(named: imgName!)
            //创建点击事件用变量保存Selcter
            let click = imageDic["click"]
//MARK: - 系统的UIBarButtonItem不支持hight状态需要自定义
//            let btnItem = UIBarButtonItem(image: img, style: UIBarButtonItemStyle.Plain, target: self, action: Selector(click!)) 
            //创建自定义的UIBarButtonItem
            let btnItem = UIBarButtonItem(imageName: imgName!, target: self, action: Selector(click!))

            items.append(btnItem)
            //添加弹簧
            let btnfix = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil)
            items.append(btnfix)
        }
        items.removeLast()
        self.toolBar.items = items
    }
    private func setupRestLenghtLabel() {
        //添加restLabel
        self.view.addSubview(restLenghtLabel)
        //添加约束
        restLenghtLabel.translatesAutoresizingMaskIntoConstraints = false
       
        self.view.addConstraint(NSLayoutConstraint(item: restLenghtLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: -25))
         self.view.addConstraint(NSLayoutConstraint(item: restLenghtLabel, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: -4))
    }
    // MARK: - 点击事件
    @objc private func toolbar() {
        print("toolbar")
    }
    @objc private func trendbutton() {
        print("trendbutton")
    }
    @objc private func mentionbutton() {
        print("mentionbutton")
    }
    @objc private func emoticonbutton(button: UIButton) {
        print("emoticonbutton")
    //MARK: - ///弹出表情键盘
        //先辞去键盘
        self.textView.resignFirstResponder()
        //点击时切换键盘  如果是系统的就切换成enmoticon
        let inputView: UIView? = textView.inputView == nil ? emoticonKeyboardView : nil
        textView.inputView = inputView
        emoticonKeyboardView.textView = self.textView
        //点击按钮切换图片compose_keyboardbutton_background  compose_emoticonbutton_background_highlighted
        var imageName: String
        if inputView == nil {
            imageName = "compose_keyboardbutton_background"
        } else {
            imageName = "compose_emoticonbutton_background"
        }
        
        button.setImage(UIImage(named: imageName), forState: UIControlState.Normal)
//        button.setImage(UIImage(named: imageName + "_highlighted"), forState: UIControlState.Highlighted)
        //延迟键盘弹出
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            self.textView.becomeFirstResponder()
        }

    }
    @objc private func add() {
        print("add")
    }
    @objc private func cancel() {
        print("取消")
        //辞去键盘
        self.textView.resignFirstResponder()
        self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func send() {
        print("发布")
        let status = self.textView.outputContentText()
        KVStatusesViewModel.sharedStatuses.sendStatuses(status) { (error) -> Void in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发送失败")
                print(error)
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
            self.navigationController?.dismissViewControllerAnimated(true, completion: { () -> Void in
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250*USEC_PER_SEC)),dispatch_get_main_queue()) { () -> Void in
                    SVProgressHUD.dismiss()
                }
            })
        }
    }

    // MARK: - 懒加载
    private lazy var titleView: UILabel = {
        let tiltleView = UILabel()
        var userName: String = ""
        //Mark: -fatal error: unexpectedly found nil while unwrapping an Optional value
        if let name = KVUserAccountViewModel.sharedUserAccountViewModel.userAccount?.screen_name {
           userName = name
        }
      
//        let userName: String = (KVUserAccountViewModel.sharedUserAccountViewModel.userAccount?.screen_name)!
        let textContent = "发微博 \n \(userName)"
        tiltleView.text = textContent
        //创建可变文本属性
        let attributedStr = NSMutableAttributedString(string: textContent)
        //        let nsUserName: NSString =  userName as NSString
        let range: NSRange = (textContent as NSString).rangeOfString(userName)
        tiltleView.textAlignment = NSTextAlignment.Center
        tiltleView.numberOfLines = 0
        tiltleView.sizeToFit()
      
        attributedStr.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(11),NSForegroundColorAttributeName: UIColor.lightGrayColor()], range: range)
        //减属性文本赋值个文本属性
        tiltleView.attributedText = attributedStr
        return tiltleView
    }()
    ///加载textView
    private lazy var textView: KVPlaceHolderTextView = {
        let textView = KVPlaceHolderTextView(frame: CGRect(x: 0, y: 0, width: UIScreen.width(), height: UIScreen.height()))
        textView.font = UIFont.systemFontOfSize(15)
        textView.delegate = self
        textView.placeHolderText = "真好玩"
        return textView
    }()
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    ///表情键盘
    private lazy var emoticonKeyboardView: KVEmoticonKeyboardView = KVEmoticonKeyboardView()
    
    ///剩余长度提示的Label
    private lazy var restLenghtLabel: UILabel = {
        let restLenghtLabel = UILabel()
        restLenghtLabel.font = UIFont.systemFontOfSize(10)
        restLenghtLabel.textColor = UIColor.lightGrayColor()
        restLenghtLabel.text = "20"
        return restLenghtLabel
    }()

}
extension KVComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        print("textViewDidChange")
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        //文字内容改变获取内容
        let contentText = self.textView.outputContentText()
        print("resultString:\(contentText)")
        let textCount: Int = contentText.characters.count
        
        //提示用户输入的长度
        let restCount = 20 - textCount
        if restCount <= 0 {
            restLenghtLabel.textColor = UIColor.redColor()
        } else {
            restLenghtLabel.textColor = UIColor.lightGrayColor()
        }
        
        restLenghtLabel.text = "\(restCount)"
        

    }
   
}